#include "tcpserver.h"
#include "log.h"
#include "log.cpp"

TCpsever::TCpsever(QObject *parent) : QObject(parent)
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    // 设置数据库端口号
    db.setPort(3306);
    // 设置数据库名
    db.setDatabaseName("serialport");
    // 设置数据库用户名
    db.setUserName("root");
    // 设置数据库密码
    db.setPassword("123456");

    if(db.open()){
        qDebug()<<"数据库打开成功";
    }
    this->serviceData=this->readDatabase(db);
    for(auto item=this->serviceData.begin();item!=this->serviceData.end();item++)
    {

        if(item.value().at(4)=="1")
        {
            this->setupTcpServer(item.key(),item.value());
        }
    }
}

QMap<int, QVector<QVariant> > TCpsever::readDatabase(QSqlDatabase db)
{
    QMap<int, QVector<QVariant>> dataContainer;
    QSqlQuery query(db); // 关联已打开的数据库连接

    // 用于存储最终的 SQL 查询语句
    QString sqlQuery;

    // 构建查询 port 表的 SQL 语句
    sqlQuery = "select * FROM port WHERE protocol = '1'";

    // 准备 SQL 查询语句，如果准备失败，输出错误信息并返回空容器
    if (!query.prepare(sqlQuery))
    {
        qDebug() << "Query preparation failed:" << query.lastError().text();
        return dataContainer;
    }

    // 执行 SQL 查询语句，如果执行失败，输出错误信息并返回空容器
    if (!query.exec())
    {
        qDebug() << "Query execution failed:" << query.lastError().text();
        return dataContainer;
    }

    // 获取查询结果的记录信息，用于获取列名和列数
    QSqlRecord record = query.record();
    // 获取查询结果的列数
    int columnCount = record.count();
    int key=0;
    // 逐行遍历查询结果
    while (query.next())
    {
        // 用于存储当前行的数据
        QVector<QVariant> rowData;

        // 遍历当前行的每一列
        for (int i = 0; i < columnCount; ++i)
        {
            // 获取当前列的值
            QVariant value = query.value(i);
            // 将值添加到 rowData 中
            rowData.append(value);
        }

        // 将当前行的数据添加到 dataContainer 中
        dataContainer[key] = rowData;
        key++;
    }

    // 返回存储查询结果的容器
    return dataContainer;
}


void TCpsever::setupTcpServer(int key,QVector<QVariant> Row)
{
    ServerManager *manager = new ServerManager;
    manager->server = new QTcpServer(manager);
    //vector的第一个参数为端口号，设置进Server
    int port = Row.at(0).toInt();
    if(!manager->server->listen(QHostAddress::Any, Row.at(0).toInt()))
    {
        qDebug()<<"TCP Server 监听失败: ";
        return;
    }

    connect(manager->server, &QTcpServer::newConnection, [manager,key,this,port]()
    {
            QTcpSocket* client = manager->server->nextPendingConnection();
            manager->clients.append(client); // 添加到客户端列表
            connect(client, &QTcpSocket::readyRead, [this, client,key,port]()
            {
                QByteArray data = client->readAll();
                m_logger->writefile(QString("%1发送%2").arg(port).arg(QString::fromUtf8(data)));
                emit serverDataReceived(key, data);
            });
            connect(client, &QTcpSocket::disconnected, [this, client,manager]()
            {
                manager->clients.removeOne(client); // 断开时移除
                client->deleteLater();
                m_logger->writefile( "Client disconnected");
            });

    });
    this->servermanager[key]=manager;
    qDebug() << "TCP Server started on port" << Row.at(0).toInt();
}

void TCpsever:: onserverDataReceived(int index, const QByteArray& data)
{
    if (servermanager.contains(index))
    {
            ServerManager* manager = servermanager[index];
                for (QTcpSocket* client : manager->clients)
                {
                    if (client->state() == QAbstractSocket::ConnectedState)
                    {
                        client->write(data);
                        m_logger->writefile(QString("[Tcp Server] Sent data to client:").arg(QString::fromUtf8(data)));
                    }
                }
    }
}
